package com.tanhua.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tanhua.app.service.UserService;
import com.tanhua.domain.UserHolder;
import com.tanhua.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override  //在控制器方法执行之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取token
        String token = request.getHeader("Authorization");
        if(StrUtil.isEmpty(token)){
            response.setStatus(401); //权限不足
            return false;
        }
        // 根据token获取登录用户
        User user = userService.findUserByToken(token);
        if(user==null){
            response.setStatus(401); //权限不足
            return false;
        }
        // 将登录用户放在threadlocal中
        UserHolder.saveUser(user);
        // 放行
        return true;
    }

    @Override  //整个响应结束执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();  //程序结束 将登录用户从线程容器中删除
    }
}
